<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/7/23
 * Time: 14:52
 */
namespace app\jujin\controller;

use controller\JunjinAdmin;
use think\Db;
use think\view\driver\Think;

class Member extends JunjinAdmin
{
    public $table='StoreMember';

    public function index()
    {
        $this->title = '用户管理';
        $get = $this->request->get();
        $db = Db::name($this->table);
        if (isset($get['nickname']) && $get['nickname'] !== '') {
            $db->whereLike('nickname', "%{$get['nickname']}%");
        }
        foreach (['type', 'status', 'phone'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->where($field, $get[$field]);
        }
        if (isset($get['create_at']) && $get['create_at'] !== '') {
            list($start, $end) = explode(' - ', $get['create_at']);
            $db->whereBetween('create_at', ["{$start} 00:00:00", "{$end} 23:59:59"]);
        }
        return parent::_list($db->order('id desc'));
    }
    protected function _data_filter(&$data)
    {
        foreach ($data as $k=>&$v){
            $v['flag_show']=show_flag($v['flag']);
        }
    }
    protected function _form_filter(&$data)
    {
        if($this->request->isGet()){
            if($this->request->get('id')){
                $this->title='编辑用户信息';
                if($data['type']==USER_TYPE_WORKER){
                    $cates = Db::table('my_cate')->where('status',1)->field('id,title')->where('pid',33)->select();
                }elseif($data['type']==USER_TYPE_SUPPLIER){
                    $cates = Db::table('my_cate')->where('status',1)->field('id,title')->where('pid',32)->select();
                }
                if(isset($cates))$this->assign('my_cate',$cates);
            }else{
                $this->title='添加用户信息';
                $data['type']=input('type');
                $data['sex']='';
            }
            $member_grade_db=Db::name('store_member_grade')->where('status',1)->field('id,name');
            if(isset($data['id'])){
                if($data['type']==USER_TYPE_WORKER){
                    //查询工人邦信息
                    $data['worker_info']=Db::name('WorkerInfo')->where('mid',$data['id'])->find();
                    $data['worker_info']['work_type_arr']=explode(',',$data['worker_info']['work_type_ids']);
                    $data['worker_info']['skill_arr']=explode(',',$data['worker_info']['skill']);
                    //查询工人邦入驻等级
                    $member_grade_db->where('type',USER_TYPE_WORKER);
                    $this->assign('two_cate_ids',$data['worker_info']['skill']);
                }elseif($data['type']==USER_TYPE_SUPPLIER){
                    //查询供应商信息
                    $data['supplier_info']=Db::name('SupplierInfo')->where('mid',$data['id'])->find();
                    $data['supplier_info']['supplier_type_arr']=explode(',',$data['supplier_info']['supplier_type_ids']);
                    $data['supplier_info']['main_arr']=explode(',',$data['supplier_info']['main']);
                    $member_grade_db->where('type',USER_TYPE_SUPPLIER);
                    $this->assign('two_cate_ids',$data['supplier_info']['main']);
                }
            }else{
                $member_grade_db->where('type',$data['type']);
            }

            $this->assign('store_member_grade',$member_grade_db->select());
        }else{
            //处理标签
            $data['flag']=isset($data['flag'])?implode(',',$data['flag']):'';
            isset($data['work_type_ids'])&&$data['work_type_ids']!=''?$data['work_type_ids']=implode(',',$data['work_type_ids']):'';
            isset($data['skill'])&&$data['skill']!=''?$data['skill']=implode(',',$data['skill']):'';
            isset($data['supplier_type_ids'])&&$data['supplier_type_ids']!=''?$data['supplier_type_ids']=implode(',',$data['supplier_type_ids']):'';
            isset($data['main'])&&$data['main']!=''?$data['main']=implode(',',$data['main']):'';
            //保存工人邦或者供应商信息
            if(isset($data['id'])){
                $this->_save_attach($data);
            }
        }
    }

    private function _save_attach($data){
        /**
         * ["name"] => string(9) "姜良熠"
        ["birthday"] => string(10) "1993-09-19"
        ["good_at"] => string(12) "擅长打杂"
        ["expiry_time"] => string(19) "2018-08-02 10:27:17"
        ["grade_id"] => string(1) "2"
         */
        if($data['type']==USER_TYPE_WORKER){
            //工人邦
            $_data['name']=$data['name'];
            $_data['birthday']=strtotime($data['birthday']);
            $_data['good_at']=$data['good_at'];
            $_data['expiry_time']=strtotime($data['expiry_time']);
            $_data['grade_id']=$data['grade_id'];
            isset($data['work_type_ids'])?$_data['work_type_ids']=$data['work_type_ids']:'';
            isset($data['skill'])?$_data['skill']=$data['skill']:'';
            Db::name('worker_info')->where('mid',$data['id'])->update($_data);
        }elseif($data['type']==USER_TYPE_SUPPLIER){
            //供应商
            $_data['name']=$data['name'];
            $_data['tel']=$data['tel'];
            $_data['intro']=$data['intro'];
            $_data['images']=$data['images']; 
            $_data['expiry_time']=strtotime($data['expiry_time']);
            $_data['grade_id']=$data['grade_id'];
            isset($data['supplier_type_ids'])?$_data['supplier_type_ids']=$data['supplier_type_ids']:'';
            isset($data['skill'])?$_data['main']=$data['skill']:'';
            Db::name('supplier_info')->where('mid',$data['id'])->update($_data);
        }
        if($data['real_address']==1){
            $credit_log=Db::name('credit_log')
                ->where('mid',$data['id'])
                ->where('type',REAL_ADDRESS_AUTHENTICATION)
                ->count();
            if($credit_log<1){
                log_credit_change($data['id'],REAL_ADDRESS_AUTHENTICATION_CREDIT,REAL_ADDRESS_AUTHENTICATION,'实地认证加信用积分');
            }
        }
    }
    /**
     * 添加/编辑成功回跳处理
     * @param bool $result
     */
    protected function _form_result($result,$data)
    {
        if ($result !== false) {
            list($base, $spm, $url,$type) = [url('@admin'), $this->request->get('spm'), url(request()->module().'/'.request()->controller().'/index'), $this->request->post('type')];
            $this->success('数据保存成功！', "{$base}#{$url}?type={$type}&spm={$spm}");
        }
    }
    public function add()
    {
        //return $this->_form($this->table, 'add');
        if($this->request->isGet()){
            $type = $this->request->param('type');
            $member_grade_db=Db::name('store_member_grade')->where('status',1)->field('id,name');
            $this->assign('store_member_grade',$member_grade_db->where('type',$type)->select());
            $cate_pid = 33;
            if($type == 2){
                $cate_pid = 32;
            }
            $cate_db = Db::table('my_cate')->where('status',1)->field('id,title');
            $my_cate = $cate_db->where('pid',$cate_pid)->select();
            foreach ($my_cate as &$item) {
                $item['_child'] = Db::table('my_cate')->where('status',1)->field('id,pid,title')->where('pid',$item['id'])->select();
            }
            $this->assign('my_cate',$my_cate);
//            $two_cate = Db::table('my_cate')
//                ->where('pid', 'IN', function ($query) use($cate_pid) {
//                    $query->table('my_cate')->where('status', 1)->where('pid',$cate_pid)->field('id');
//                })
//                ->select();
            $this->assign('type',$type);
            return $this->fetch('add');
        }else{
            //POST 提交
            $param = $this->request->post();
            //dump($param);
            if(!isset($param['flag'])){
                $param['flag']='';
            }else{
                $param['flag']=implode(',',$param['flag']);
            }
            $userdata = [
                'openid'=>createRandomStr(28,0),
                'phone'=>$param['phone'],
                'nickname'=>$param['nickname'],
                'headimg'=>$param['headimg'],
                'sex'=>$param['sex'],
                'province'=>$param['province'],
                'city'=>$param['city'],
                'district'=>$param['area'],
                'address'=>$param['address'],
                'flag'=>$param['flag'],
                'sort'=>$param['sort'],
                'lat'=>$param['lat'],
                'lng'=>$param['lng'],
                'type'=>$param['type']
            ];
            if(Db::name('store_member')->where('phone',$param['phone'])->find()){
                $this->error('手机号重复！');
            }
//            dump($userdata);
//            exit();
            Db::startTrans();
            if(!isset($param['twocate'])){
                $this->error('请选择分类');
            }
            $re = $re1 = false;
            $re = Db::table('store_member')->insertGetId($userdata);
            if($re){
                if($param['type'] == 1){
                   $re1 = Db::table('worker_info')->insert([
                        'mid'=>$re,
                        'name'=>$param['name'],
                        'work_type_ids'=>implode(',',$param['onecate']),
                        'skill'=>implode(',',$param['twocate']),
                        'work_price'=>$param['work_price'],
                        'birthday'=>strtotime($param['birthday']),
                        'good_at'=>$param['good_at'],
                        'expiry_time'=>strtotime($param['expiry_time']),
                        'grade_id'=>$param['grade_id']
                    ]);
                }elseif ($param['type'] == 2){
                    $re1 = Db::table('supplier_info')->insert([
                        'mid'=>$re,
                        'name'=>$param['name'],
                        'supplier_type_ids'=>implode(',',$param['onecate']),
                        'main'=>implode(',',$param['twocate']),
                        'tel'=>$param['tel'],
                        'intro'=>$param['intro'],
                        'images'=>$param['images'],
                        'expiry_time'=>strtotime($param['expiry_time']),
                        'grade_id'=>$param['grade_id']
                    ]);
                }
            }
            if(!empty($re) && !empty($re1)){
                Db::commit();
                list($base, $spm, $url,$type) = [url('@admin'), $this->request->get('spm'), url(request()->module().'/'.request()->controller().'/index'), $this->request->post('type')];
                $this->success('数据保存成功！', "{$base}#{$url}?type={$type}&spm={$spm}");
            }else{
                Db::rollback();
                $this->error('数据保存失败！');
            }
        }
    }
    function choose_position(){
        return $this->fetch();
    }
}